#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <pthread.h>
int sockfd;
char name[20];
void sigin()
{
	close(sockfd);
	exit(0);
}
void* send_to(void* str)
{
	int clifd = *(int*)str;
	for(;;)
	{
		printf("\r");
		char buf[1024] = {};
		char temp[1024]={};
		printf(">");
		gets(temp);
		
		sprintf(buf,"%s:%s",name,temp);
		write(sockfd,buf,strlen(buf)+1);
		
	}

}
void* recv_from(void* str)
{
	int clifd = *(int*)str;
	char buf[256]={};
	for(;;)
	{

		printf("read:");
		read(sockfd,buf,sizeof(buf));
		printf("\r%s\n",buf);
	}
}
int main()
{
	signal(2,sigin);
	printf("服务器创建socket...\n");
	sockfd = socket(AF_INET,SOCK_STREAM,0);
	if(0 > sockfd)
	{
		perror("socket");
		return -1;
	}

	printf("准备地址...\n");
	struct sockaddr_in addr = {};
	addr.sin_family = AF_INET;
	addr.sin_port = htons(6888);
	addr.sin_addr.s_addr = inet_addr("106.15.75.133");
	socklen_t len = sizeof(addr);

	printf("绑定连接服务器...\n");
	if(connect(sockfd,(struct sockaddr*)&addr,len))
	{
		perror("connect");
		return -1;
	}
	printf("请输入你的骚包网名：");
	gets(name);
	pthread_t pid[2];
	pthread_create(&pid[0],NULL,send_to,&sockfd);
	usleep(100);
	pthread_create(&pid[2],NULL,recv_from,&sockfd);
	for(;;)
	{
	}
}
